package net.xepherx.ytdl;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneLayout;

import org.json.JSONArray;
import org.json.JSONObject;

public class MainView implements KeyListener{
	private JPanel container;
	private JFrame window;
	private int videos = 0;
	boolean ctrlDown = false, vDown = false, pasted = false;
	private MainModel mm;
	public MainView(){
		buildGui();
	}
	public MainView(MainModel mm){
		buildGui();
		setData(mm);
	}
	
	public void buildGui(){
		window = new JFrame();
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.setPreferredSize(new Dimension(800,600));
		window.setMinimumSize(new Dimension(600,400));
		window.setBackground(new Color(0xffffff));
		window.addKeyListener(this);
		
		container = new JPanel();
		JScrollPane jsp = new JScrollPane(container, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		jsp.setLayout(new ScrollPaneLayout());
		JPanel wrapper = new JPanel();
		wrapper.setLayout(new BorderLayout());

		jsp.getVerticalScrollBar().setUnitIncrement(16);
		container.setLayout(new GridBagLayout());
		
		
		
		wrapper.add(container, BorderLayout.NORTH);
		
		jsp.add(wrapper);
		jsp.setViewportView(wrapper);
		jsp.getViewport().setPreferredSize(window.getPreferredSize());
		
		
		window.add(jsp);
		window.pack();
		
		window.setVisible(true);
		
		window.setLocationRelativeTo(null);
		refresh();
	}
	
	public void addVideo(Component video){
		container.add(video, GridBagConstraintsFactory.videoPanelConstraints(videos+1));
		
		videos++;
		refresh();
	}
	
	public void addMetapanel(){
		window.add(new MetaPanel(),BorderLayout.NORTH);
	}

	public void setData(MainModel mm) {
		this.mm = mm;
		container.removeAll();
		for(Video v : mm.getVideos()){
			VideoPanel vid = new VideoPanel(v);
			vid.setTitle(v.getTitle());
			vid.setAuthor(v.getUploader());
			addVideo(vid);
			container.repaint();
		}
		refresh();
		
	}
	
	public void addToData(Video v){
		this.mm.addVideo(v);

		VideoPanel vid = new VideoPanel(v);
		vid.setTitle(v.getTitle());
		vid.setAuthor(v.getUploader());
		addVideo(vid);
		
		
	}
	
	public void clearData(){
		this.mm.removeAll();
		container.removeAll();
		refresh();
	}
	
	public void refresh(){
		container.revalidate();
		container.repaint();
		window.revalidate();
		window.repaint();
		
		
		
	}
	@Override
	public void keyPressed(KeyEvent arg0) {
		if(arg0.getKeyCode() == 17){
			ctrlDown = true;
		}else if(arg0.getKeyCode() == 86 && ctrlDown){
			vDown = true;
		}
		
		
		
		if(ctrlDown && vDown && !pasted){

			pasted = true;
			
			try {
				String clipboard = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
				
				String playlistId = null;
				String videoId = null;
				
				final String playlistBaseUrl = "https://gdata.youtube.com/feeds/api/playlists/%s?alt=json&start-index=1&max-results=50";

				
				Pattern p2 = Pattern.compile("(?:\\?|&)v=([^&]*)");
				Matcher m2 = p2.matcher(clipboard);
				while(m2.find()){
					videoId = m2.group(1);
				}
				
				
				if(videoId != null){
					mm.addVideo(new Video(clipboard));
					setData(mm);
				} else {
					Pattern p = Pattern.compile("(?:\\?|&)list=([^&]*)");
					Matcher m = p.matcher(clipboard);
					
					while(m.find()){
						playlistId = m.group(1);
					}
					if(playlistId != null){
						//
						
						//System.out.println(t);
						
						final String t = Utils.getUrlContent(new URL(String.format(playlistBaseUrl, playlistId)));
						
						
						
						
						new Thread(){
							JSONArray entries = new JSONObject(t).getJSONObject("feed").getJSONArray("entry");
							
							public void run(){
								for(int i = 0; i < entries.length() - 1; i++){
									String href = entries.getJSONObject(i).getJSONArray("link").getJSONObject(0).get("href").toString();
									Video vid = null;
									try {
										 vid = new Video(href);
									} catch (Exception e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
									addToData(vid);
								}
								
								refresh();
							}
						}.start();
						
						
						
						
						
					} else {
						throw new Exception("invalid url");
					}
				}
				
				
				
				
				
				
				refresh();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		
	}
	@Override
	public void keyReleased(KeyEvent arg0) {
		if(arg0.getKeyCode() == 17){
			ctrlDown = false;
		} else if(arg0.getKeyCode() == 86){
			vDown = false;
		}
		
		if(!vDown && pasted){
			pasted = false;
			
		}
		
	}
	@Override
	public void keyTyped(KeyEvent arg0) {
		
		
	}
}
